package com.googlecode.garbagecan.commons.execstudy;

import org.apache.commons.exec.*;

import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Sample6 {
	
	private static Logger logger = Logger.getLogger(Sample6.class.getName());
	
	public static void main(String[] args) {
		String shellFile = Sample6.class.getResource("/com/googlecode/garbagecan/commons/execstudy/Sample6.sh").getFile();
		test(shellFile + " 0");
		test(shellFile + " 1");
		test(shellFile + " 255");
	}

	public static void test(String cmd) {
		CommandLine cmdLine = CommandLine.parse(cmd);

		DefaultExecutor executor = new DefaultExecutor();
		executor.setExitValues(null);
		ExecuteWatchdog watchdog = new ExecuteWatchdog(5 * 1000);
		executor.setWatchdog(watchdog);
		
		LogOutputStream stdoutHandler = new LogOutputStream() {
			@Override
			protected void processLine(String line, int level) {
				logger.log(Level.INFO, line);
			}
		};
		
		LogOutputStream stderrHandler = new LogOutputStream() {
			@Override
			protected void processLine(String line, int level) {
				logger.log(Level.INFO, line);
			}
		};
		
		PumpStreamHandler streamHandler = new PumpStreamHandler(stdoutHandler, stderrHandler);
		executor.setStreamHandler(streamHandler);
		
		DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
		
		try {
			executor.execute(cmdLine, resultHandler);
		} catch (ExecuteException e) {
			logger.log(Level.SEVERE, e.getMessage(), e);
		} catch (IOException e) {
			logger.log(Level.SEVERE, e.getMessage(), e);
		}
		
		try {
			resultHandler.waitFor(10 * 1000);
		} catch (InterruptedException ex) {
			logger.log(Level.SEVERE, null, ex);
		}
		
		logger.log(Level.INFO, "Has result: " + resultHandler.hasResult());
		if (resultHandler.hasResult()) {
			logger.log(Level.INFO, "Exit value: " + resultHandler.getExitValue());
			logger.log(Level.INFO, "Exception: " + resultHandler.getException());
			logger.log(Level.INFO, "Killed Process: " + watchdog.killedProcess());
		}
		logger.log(Level.INFO, "isFailure: " + executor.isFailure(1));
	}
}
